from flask import request, render_template, jsonify, redirect, url_for, send_from_directory
from flask.views import MethodView, View
import myblog.models
from blogmanage.forms import BlogForms
import os
from datetime import datetime
from reguser.checklimit import check_limit
UPLOAD_FOLDER = r'./static/uploads'
ALLOWEd_EXTENSIONS = ['.jpg', '.gif', '.png']


# 检查文件是否为图片
def allowed_file(filename):
    _, ext = os.path.splitext(filename)
    return ext.lower() in ALLOWEd_EXTENSIONS


# 上传图片
class SendFile(MethodView):
    def get(self, filename):
        return send_from_directory(UPLOAD_FOLDER, filename)


class BlogList(MethodView):
    def get(self, page=1):
        if check_limit() == 1:
            return redirect(url_for('admin.login'))
        if check_limit() == 2:
            return redirect(url_for('waring'))
        arts = myblog.models.Article.query.order_by(myblog.models.Article.id.desc()).paginate(page, per_page=10)
        cates = myblog.models.db.session.query(myblog.models.Category).all()
        numcomment = myblog.models.Message.query.count()
        return render_template('blogmanage/bloglist.html', cates=cates, arts=arts, numcomment=numcomment)


class CateList(MethodView):
    def get(self, id=1):
        if check_limit() == 1:
            return redirect(url_for('admin.login'))
        if check_limit() == 2:
            return redirect(url_for('waring'))
        arts = myblog.models.Article.query.filter(myblog.models.Article.categoryid == id).order_by(
            myblog.models.Article.id.desc()).all()
        cates = myblog.models.db.session.query(myblog.models.Category).all()
        numcomment = myblog.models.Message.query.count()
        return render_template('blogmanage/cateblog.html', cates=cates, arts=arts, numcomment=numcomment)


class BlogEdit(View):
    methods = ['GET', 'POST']

    def dispatch_request(self, id=0):
        check_limit()
        cates = myblog.models.db.session.query(myblog.models.Category).all()
        numcomment = myblog.models.Message.query.count()

        art = myblog.Article.query.filter(myblog.Article.id == id).one_or_none()
        form = BlogForms(request.form, obj=art)
        form.categoryid.choices = [(cate.id, cate.categoryname) for cate in myblog.Category.query.all()]
        if request.method == 'POST':
            form = BlogForms(request.form)
            img_path = None
            if request.files.get('faceimage'):
                img = request.files.get('faceimage')
                if img and allowed_file(img.filename):
                    img_path = datetime.now().strftime('%Y%m%d%H%M%S') + os.path.splitext(img.filename)[1]
                    img.save(os.path.join(UPLOAD_FOLDER, img_path))
            form.faceimage.data = img_path
            form.body.data = form.body.data.replace('\r', '').replace('\n', '<br/>')
            art = myblog.Article.query.get(id)
            form.populate_obj(art)
            myblog.db.session.commit()
            return redirect(url_for('.blog_list'))
        return render_template('blogmanage/blogedit.html', cates=cates, numcomment=numcomment, form=form, art=art)


class BlogDel(MethodView):
    def get(self, id=0):

        art = myblog.models.Article()
        if id:
            art = myblog.models.Article.query.get(id)
            if art:
                myblog.models.db.session.delete(art)
                myblog.models.db.session.commit()
        return redirect(url_for('.blog_list'))


class MsgDel(MethodView):
    def get(self, id=0):

        if id:
            msg = myblog.models.Message.query.get(id)
            if msg:
                myblog.models.db.session.delete(msg)
                myblog.models.db.session.commit()
        return redirect(url_for('.message_list'))


class MessageList(MethodView):
    def get(self, page=1):
        if check_limit() == 1:
            return redirect(url_for('admin.login'))
        if check_limit() == 2:
            return redirect(url_for('waring'))
        cates = myblog.models.db.session.query(myblog.models.Category).all()
        numcomment = myblog.models.Message.query.count()
        messages = myblog.models.Message.query.order_by(myblog.models.Message.id.desc()).paginate(page, per_page=8)
        return render_template('blogmanage/messagelist.html', messages=messages, cates=cates, numcomment=numcomment)
